from __future__ import annotations
import smtplib
from email.mime.text import MIMEText
from email.header import Header

from . import config as cfg


def _quit_safely(server: smtplib.SMTP) -> None:
    try:
        try:
            server.quit()
        except smtplib.SMTPServerDisconnected:
            server.close()
        except smtplib.SMTPResponseException:
            server.close()
    except Exception:
        # 避免退出阶段异常中断主流程
        try:
            server.close()
        except Exception:
            pass


def send_email(subject: str, body: str) -> None:
    cfg.validate_email_config()

    message = MIMEText(body, _subtype="plain", _charset="utf-8")
    message["Subject"] = Header(subject, "utf-8")
    message["From"] = cfg.EMAIL_FROM
    message["To"] = cfg.EMAIL_TO

    if cfg.SMTP_USE_SSL:
        server = smtplib.SMTP_SSL(cfg.SMTP_HOST, cfg.SMTP_PORT, timeout=30)
        try:
            server.ehlo()
            server.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
            server.sendmail(cfg.EMAIL_FROM, [cfg.EMAIL_TO], message.as_string())
        finally:
            _quit_safely(server)
    else:
        server = smtplib.SMTP(cfg.SMTP_HOST, cfg.SMTP_PORT, timeout=30)
        try:
            server.ehlo()
            if cfg.SMTP_USE_TLS:
                server.starttls()
                server.ehlo()
            server.login(cfg.SMTP_USERNAME, cfg.SMTP_PASSWORD)
            server.sendmail(cfg.EMAIL_FROM, [cfg.EMAIL_TO], message.as_string())
        finally:
            _quit_safely(server)